package com.bitrate.dagger.kaptcha.server;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bitrate.dagger.kaptcha.dto.KaptchaResponseDTO;
import com.google.code.kaptcha.impl.DefaultKaptcha;

@Component
public class KaptchaServer {

	@Autowired
	private DefaultKaptcha defaultKaptcha;

	public KaptchaResponseDTO execute() {
		KaptchaResponseDTO dto = new KaptchaResponseDTO();
		String base64Image = "";
		String code = defaultKaptcha.createText();
		BufferedImage bfImage = defaultKaptcha.createImage(code);
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		try {
			ImageIO.write(bfImage, "jpg", bs);
			base64Image = Base64.getEncoder().encodeToString(bs.toByteArray());
			bs.close();
		} catch (IOException e) {
			e.printStackTrace();
			return dto.setFlag(false);
		}
		dto.setBase64Image(base64Image).setCode(code);
		return dto;
	}

}
